//
//  XKTitleView.swift
//  XKPageView
//
//  Created by 徐凯 on 2017/6/6.
//  Copyright © 2017年 XK. All rights reserved.
//

import UIKit

class XKTitleView: UIView {

    fileprivate var titles : [String]
    fileprivate var style : XKPageStyle
    fileprivate lazy var scrollView : UIScrollView = {
        let scrollView = UIScrollView(frame: self.bounds)
        scrollView.scrollsToTop = false // 点击状态栏回到最上
        scrollView.showsHorizontalScrollIndicator = false

        return scrollView
    }()
    
    
    init(frame : CGRect, titles : [String], style : XKPageStyle) {
        
        self.titles = titles
        self.style = style
        super.init(frame: frame)
        setupUI()
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}


extension XKTitleView
{
    fileprivate func setupUI()
    {
        addSubview(scrollView)
        setupTitleLabs()
        
    }
    
    private func setupTitleLabs()
    {
        var titleLabs : [UILabel] = [UILabel]()
        for (i, title) in titles.enumerated()
        {
            let titleLabel = UILabel()
            titleLabel.text = title
            titleLabel.tag = i
            titleLabel.textAlignment = .center
            titleLabel.textColor = i==0 ? style.selectColor : style.normaColor
            titleLabel.font = style.titleFont
            
            scrollView.addSubview(titleLabel)
            titleLabs.append(titleLabel)
            let tapGes = UITapGestureRecognizer(target: self, action: #selector(titleLabClick(tag:)))
            titleLabel.addGestureRecognizer(tapGes)
            
        }
        
        
        // 设置frame
        var labW : CGFloat = bounds.width / CGFloat(titles.count)
        var labH : CGFloat = style.titleHight
        var labX : CGFloat = 0
        var labY : CGFloat = 0
        for (i, lab) in titleLabs.enumerated()
        {
            if style.isScrollEnable // 可以滚动
            {
                
                labW = (lab.text! as NSString).boundingRect(with: CGSize(width: CGFloat(MAXFLOAT), height: 0), options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName : style.titleFont], context: nil).width
                labX = i==0 ? style.titleMargin : titleLabs[i - 1].frame.maxX + style.titleMargin
            }
            else // 不能滚
            {
                labX = labW * CGFloat(i)
            }
            lab.frame = CGRect(x: labX, y: labY, width: labW, height: labH)
            
        }
        
        if(style.isScrollEnable)
        {
            scrollView.contentSize = CGSize(width: titleLabs.last!.frame.maxX + style.titleMargin, height: 0)
        }
    }
    
}


// MARK:- 事件
extension XKTitleView
{
    @objc fileprivate func titleLabClick(tag : UITapGestureRecognizer)
    {
        
        guard let selectLab = tag.view as? UILabel else {
            return
        }
       
        print(selectLab.tag)
    }
}
